// 显示欢迎词
window.onload = function() {
  const chatBox = document.getElementById('chat-box');
  const welcomeMessage = "欢迎使用聊天对话系统！你可以在这里提出任何问题，我会尽力帮助你。";
  chatBox.innerHTML += `<div class="assistant"><strong>大模型:</strong> ${marked.parse(welcomeMessage)}</div>`;
};

async function sendMessage() {
  const userInput = document.getElementById('user-input').value;
  const chatBox = document.getElementById('chat-box');
  const selectedModel = document.getElementById('model-select').value;
  console.log(selectedModel);
  if (!userInput.trim()) {
    alert('请输入内容');
    return;
  }

  // 显示用户输入
  const userMessage = marked.parse(userInput);
  chatBox.innerHTML += `<div class="user"><strong>你:</strong> ${userMessage}</div>`;
  document.getElementById('user-input').value = '';

  // 显示加载指示器
  chatBox.innerHTML += `<div class="loading"><strong>大模型:</strong> 正在思考中...</div>`;
  const loadingDiv = chatBox.lastElementChild;

  // 配置请求选项
  const options = {
    method: 'POST',
    headers: {
      Authorization: modelkey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: selectedModel,
      messages: [{ role: "user", content: userInput }],
      stream: false,
      max_tokens: 512,
      stop: ["null"],
      temperature: 0.7,
      top_p: 0.7,
      top_k: 50,
      frequency_penalty: 0.5,
      n: 1,
      response_format: { type: "text" },
      tools: [{ type: "function", function: { description: "<string>", name: "<string>", parameters: {}, strict: false } }]
    })
  };

  // 发送请求到硅基流动的接口
  try {
    const response = await fetch(modelapi, options);
    const data = await response.json();
    
    // 移除加载指示器
    loadingDiv.remove();

    // 显示大模型的回复
    const assistantMessage = marked.parse(data.choices[0].message.content);
    chatBox.innerHTML += `<div class="assistant"><strong>大模型:</strong> ${assistantMessage}</div>`;
    chatBox.scrollTop = chatBox.scrollHeight;
  } catch (error) {
    // 移除加载指示器
    loadingDiv.remove();

    chatBox.innerHTML += `<div class="assistant"><strong>错误:</strong> 无法获取大模型的回复</div>`;
  }
}